import React from 'react'
import { Field, VoidField } from '@formily/react'
import { FormItem, Select, FormLayout } from '@formily/antd'
import { Space, InputNumber } from 'antd'
import { useT } from '@designable/event-system'
import { connect, mapProps } from '@formily/react'
import { observer } from '@formily/reactive-react'
import { useEffect, useRef } from 'react'

const Com = observer(
  (props: {
    nameCount: string
    nameUnit: string
    namePost: string
    addonTextBefore: string
    middleText: string
    options?: any[]
    required?: boolean
    title?: string
  }) => {
    const {
      nameCount,
      nameUnit,
      namePost,
      addonTextBefore,
      middleText,
      options,
      required,
      title,
    } = props
    const $t = useT()
    const fieldCacheRef = useRef<any>(null)

    useEffect(() => {
      fieldCacheRef.current?.setDataSource(options)
    }, [options])

    return (
      <VoidField
        name={`containerFixedDuration`}
        title={<>{required && <span className='ant-formily-item-asterisk'>*</span>}{title}</>}
        decorator={[FormItem]}
      >
        <Space align="start">
          {$t(addonTextBefore)}
          <Field
            required={required}
            name={namePost}
            decorator={[FormItem]}
            component={[
              InputNumber,
              {
                min: 0,
                style: { width: 100 },
              },
            ]}
          />
          {$t(middleText)}
          <Field
            required={required}
            name={nameCount}
            decorator={[FormItem]}
            component={[
              InputNumber,
              {
                min: 1,
                style: { width: 100 },
              },
            ]}
          />
          <Field
            required={required}
            name={nameUnit}
            decorator={[FormItem]}
            reactions={(field) => {
              fieldCacheRef.current = field
            }}
            component={[
              Select,
              {
                style: { width: 100 },
                placeholder: $t('请选择'),
              },
            ]}
          />
        </Space>
      </VoidField>
    )
  }
)

export const AfterPurchaseFixedDuration = connect(
  Com,
  mapProps({
    title: 'title',
  })
)
